package sg.edu.nus.comp.qa;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import sg.edu.nus.comp.qa.calculator.Calculator;
import sg.edu.nus.comp.qa.calculator.StringDistanceCalculator;
import sg.edu.nus.comp.qa.calculator.WordDistanceCalculator;
import sg.edu.nus.comp.qa.calculator.WordDistanceCalculatorV2;
import sg.edu.nus.comp.qa.question.ComparableQuestion;
import sg.edu.nus.comp.qa.utils.StopWordsSet;

public class QASorter {
	public static final List<Calculator> CALCULATORS = new ArrayList<Calculator>(); 
	private final Map<String, List<Integer>> questionMap = QAInitializer.SINGLETON.getQuestionMap();
	private final List<ComparableQuestion> questionList = QAInitializer.SINGLETON.getQuestionList();
	static{
		//CALCULATORS.add(new WordDistanceCalculator());
		CALCULATORS.add(new WordDistanceCalculatorV2());
		//CALCULATORS.add(new StringDistanceCalculator());
	}
	
	public List<ComparableQuestion> sort(String target){
		target = StopWordsSet.getStopWordSet().removeStopWords(target);
		List<ComparableQuestion> selectedQuestionList = selectList(target);
		for(Calculator cal : CALCULATORS){
			for(ComparableQuestion q : selectedQuestionList){
				q.setValue(q.getValue()+cal.calculate(q.getQuestion(), target));
			}
		}
		Collections.sort(selectedQuestionList);
		return selectedQuestionList;
	}

	private List<ComparableQuestion> selectList(String target) {
		List<ComparableQuestion> selectedQuestionList = new ArrayList<ComparableQuestion>();
		List<Integer> questionIds = new ArrayList<Integer>();
		String[] words = target.split("[^a-zA-Z\\d:]");
		for(String word: words){
			if(questionMap.containsKey(word)){
				List<Integer> questions = questionMap.get(word);
				for(int q : questions){
					if(!questionIds.contains(q)){
						questionIds.add(q);
						selectedQuestionList.add(questionList.get(q));
					}
				}
			}
		}
		return selectedQuestionList;
	}

}
